package letcode.problem.dynamicProgra;

import java.util.List;

/**
 * https://leetcode.cn/problems/triangle/description/?envType=study-plan-v2&envId=dynamic-programming
 * */
public class Triangle {
    /**
     * 动态规划出 算出每行三角形最小值
     * 在最后一行取最小值 即为全局最小值
     * */
    public static int minimumTotal(List<List<Integer>> triangle) {
        if (triangle.size() == 1) {
            return triangle.get(0).get(0);
        }

        int[][] miniPath = new int[triangle.size()][triangle.size()];
        miniPath[0][0] = triangle.get(0).get(0);
        for (int i = 1; i < triangle.size(); i++) {
            miniPath[i][0] = miniPath[i - 1][0] + triangle.get(i).get(0);
            for (int j = 1; j < i; j++) {
                miniPath[i][j] = Math.min(miniPath[i - 1][j - 1], miniPath[i - 1][j]) + triangle.get(i).get(j);
            }
            miniPath[i][i] = miniPath[i - 1][i - 1] + triangle.get(i).get(i);
        }
        int minTotal = miniPath[triangle.size() - 1][0];
        for (int i = 1; i < triangle.size(); ++i) {
            minTotal = Math.min(minTotal, miniPath[triangle.size() - 1][i]);
        }
        // 返回最小路径和
        return minTotal;
    }
}
 